//
//  TestView.swift
//  Runner
//
//  Created by 李旭峰 on 2020/7/9.
//

import UIKit
import Flutter
import SnapKit
import RxSwift
import RxCocoa

class TestView: NSObject {
    private let dispose = DisposeBag()
    static let viewName:String = "plugins.com.asman/test_view"
    static let viewChannelName:String = "samples.flutter.io/testViewChannel"
    private let frame:CGRect
    private let viewID:Int64
    private let args:Any?
    var messenger:FlutterBinaryMessenger
    private var myView:UIView = UIView()
    private var isDidInit:Bool = false
    
    init(_ frame:CGRect,viewID:Int64,args:Any?,binaryMessenger:FlutterBinaryMessenger) {
        self.frame = frame
        self.viewID = viewID
        self.args = args
        self.messenger = binaryMessenger
        super.init()
        initMathodChannel()
    }
    
    private func initMathodChannel(){
        let channel = FlutterMethodChannel.init(name: "plugins.com.asman/testViewChannel_\(self.viewID)", binaryMessenger: self.messenger)
        
    }
    private func initMyView(){
        self.myView.frame = self.frame
        self.myView.backgroundColor = UIColor.gray
        let textField = UITextField()
        textField.textColor = UIColor.purple
        textField.backgroundColor = UIColor.white
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.keyboardType = UIKeyboardType.numberPad
        self.myView.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(20)
//            make.trailing.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(40)
        }
        let btn = UIButton(type: .custom)
        btn.setTitle("send", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.backgroundColor = UIColor.blue
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        self.myView.addSubview(btn)
        btn.snp.makeConstraints { (make) in
            make.centerY.height.equalTo(textField)
            make.leading.equalTo(textField.snp.trailing).offset(10)
            make.width.equalTo(60)
            make.trailing.equalToSuperview().offset(-20)
        }
        btn.rx.tap.subscribe(onNext: {[weak self] in
            guard let `self` = self else { return }
            let height = textField.text?.decimal.cgfloat ?? 0
            print("reset height : \(height)")
        }).disposed(by: self.dispose)
    }
    deinit {
        
    }
}

extension TestView : FlutterPlatformView {
    func view() -> UIView {
        if !self.isDidInit {
            self.isDidInit = true
            self.initMathodChannel()
            self.initMyView()
        }
        return self.myView
    }
}
